package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.UserLike;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.enums.SexEnum;
import com.tanhua.server.mapper.SettingsMapper;
import com.tanhua.server.pojo.*;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.*;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UsersService {

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private SettingsService settingsService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private BlackListService blackListService;


    /**
     * 查看资料
     *
     * @param userID    用户id
     * @param huanxinID 环信id
     * @return
     */
    public UserInfoVo queryUserInfo(String userID, String huanxinID) {
        //获取当前登录用户id
        User user = UserThreadLocal.get();
        //当传来的id 和环信id都为空,则代表用户在查自己的用户信息
        Long userId = user.getId();
        //如果传来的userid不为空,则将该用户id赋值给userId
        if (StringUtils.isNotBlank(userID)) {
            userId = Long.valueOf(userID);
        } else if (StringUtils.isNotBlank(huanxinID)) {
            //如果环信id不为空,也赋值
            userId = Long.valueOf(huanxinID);
        }

        //调用方法获取用户信息对象
        UserInfo userInfo = this.userInfoService.queryById(userId);

        //如果不为空,则将查到用户信息对象封装给UserInfoVo
        if (null == userInfo) {
            return null;
        }

        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setAge(userInfo.getAge() != null ? userInfo.getAge().toString() : null);
        userInfoVo.setAvatar(userInfo.getLogo());
        userInfoVo.setBirthday(userInfo.getBirthday());
        userInfoVo.setEducation(userInfo.getEdu());
        userInfoVo.setCity(userInfo.getCity());
        userInfoVo.setGender(userInfo.getSex().name().toLowerCase());
        userInfoVo.setId(userInfo.getUserId());
        userInfoVo.setIncome(userInfo.getIncome() + "K");
        userInfoVo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
        userInfoVo.setNickname(userInfo.getNickName());
        userInfoVo.setProfession(userInfo.getIndustry());

        return userInfoVo;
    }

    /**
     * 更新资料
     *
     * @param userInfoVo
     * @return
     */
    public Boolean updateUserInfo(UserInfoVo userInfoVo) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setAge(Integer.valueOf(userInfoVo.getAge()));
        userInfo.setSex(StringUtils.equalsIgnoreCase(userInfoVo.getGender(), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setBirthday(userInfoVo.getBirthday());
        userInfo.setCity(userInfoVo.getCity());
        userInfo.setEdu(userInfoVo.getEducation());
        userInfo.setIncome(StringUtils.replace(userInfoVo.getIncome(), "K", ""));
        userInfo.setIndustry(userInfoVo.getProfession());
        userInfo.setMarriage(userInfoVo.getMarriage() == 1 ? "已婚" : "未婚");
        return this.userInfoService.updateUserInfoByUserId(userInfo);
    }

    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     *
     * @return
     */
    public CountsVo queryCounts() {
        User user = UserThreadLocal.get();
        CountsVo countsVo = new CountsVo();
        countsVo.setEachLoveCount(this.userLikeApi.queryEachLikeCount(user.getId()));
        countsVo.setLoveCount(this.userLikeApi.queryLikeCount(user.getId()));
        countsVo.setFanCount(this.userLikeApi.queryFanCount(user.getId()));

        return countsVo;

    }

    /**
     * 查看1 互相关注 2 我关注 3 粉丝 4 谁看过我
     *
     * @param valueOf  1 互相关注 2 我关注 3 粉丝 4 谁看过我
     * @param page
     * @param pageSize
     * @param nickname
     * @return
     */
    public PageResult queryLikeList(Integer valueOf, Integer page, Integer pageSize, String nickname) {

        User user = UserThreadLocal.get();
        PageResult pageResult = new PageResult();
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        List<Long> idList = new ArrayList<>();
        if (valueOf == 1) {
            PageInfo<UserLike> pageInfo = this.userLikeApi.queryEachLikeList(user.getId(), page, pageSize);
            List<UserLike> records = pageInfo.getRecords();
            for (UserLike record : records) {
                Long likeUserId = record.getUserId();
                idList.add(likeUserId);
            }
        } else if (valueOf == 2) {
            PageInfo<UserLike> pageInfo = this.userLikeApi.queryLikeList(user.getId(), page, pageSize);
            List<UserLike> records = pageInfo.getRecords();
            for (UserLike record : records) {
                Long likeUserId = record.getLikeUserId();
                idList.add(likeUserId);
            }
        } else if (valueOf == 3) {
            PageInfo<UserLike> pageInfo = this.userLikeApi.queryFanList(user.getId(), page, pageSize);
            List<UserLike> records = pageInfo.getRecords();
            for (UserLike record : records) {
                Long likeUserId = record.getUserId();
                idList.add(likeUserId);
            }
        } else if (valueOf == 4) {
            PageInfo<Visitors> pageInfo = this.visitorsApi.topVisitor(user.getId(), page, pageSize);
            List<Visitors> records = pageInfo.getRecords();
            for (Visitors record : records) {
                Long visitorUserId = record.getVisitorUserId();
                idList.add(visitorUserId);
            }
        }

        if (idList.size() == 0) {
            pageResult.setItems(null);
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", idList);

        if (StringUtils.isNotEmpty(nickname)) {
            queryWrapper.eq("nick_name", nickname);
        }
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);

        List<UserLikeVo> userLikeVos = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            UserLikeVo userLikeVo = new UserLikeVo();
            userLikeVo.setId(userInfo.getId().intValue());
            userLikeVo.setAvatar(userInfo.getLogo());
            userLikeVo.setNickname(userInfo.getNickName());
            userLikeVo.setGender(userInfo.getSex().name().toLowerCase());
            userLikeVo.setAge(userInfo.getAge());
            userLikeVo.setCity(userInfo.getCity());
            userLikeVo.setEducation(userInfo.getEdu());
            userLikeVo.setMarriage(userInfo.getMarriage().equals("已婚") ? 1 : 0);
            double queryScore = this.recommendUserService.queryScore(user.getId(), userInfo.getUserId());
            if (queryScore == 0) {
                queryScore = RandomUtils.nextDouble(70, 90);
            }
            userLikeVo.setMatchRate((int) queryScore);

            userLikeVos.add(userLikeVo);

        }
        pageResult.setItems(userLikeVos);
        return pageResult;
    }

    /**
     * 取消喜欢
     *
     * @param uid
     * @return
     */
    public Boolean deleteLike(Long uid) {
        User user = UserThreadLocal.get();
        return this.userLikeApi.deleteUserLike(user.getId(), uid);
    }

    /**
     * 粉丝喜欢
     *
     * @param uid 选的id
     */
    public String likeFan(Long uid) {
        User user = UserThreadLocal.get();
        String id = this.userLikeApi.saveUserLike(user.getId(), uid);
        return id;
    }


    /**
     * 查询通用设置
     *
     * @return
     */
    public SettingsVo querySettings() {
        User user = UserThreadLocal.get();
        SettingsVo settingsVo = new SettingsVo();
        settingsVo.setId(user.getId());
        settingsVo.setPhone(user.getMobile());

        Settings settings = this.settingsService.queryById(user.getId());
        if (null != settings) {
            settingsVo.setLikeNotification(settings.getLikeNotification());
            settingsVo.setPinglunNotification(settings.getPinglunNotification());
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification());
        }

        //查询问题
        Question question = this.questionService.queryQuestion(user.getId());
        if (null != question) {
            settingsVo.setStrangerQuestion(question.getTxt());
        }

        return settingsVo;
    }

    /**
     * 保存问题
     *
     * @param content 问题内容
     */
    public Boolean saveQuestions(String content) {
        User user = UserThreadLocal.get();
        return this.questionService.saveQuestion(user.getId(), content);
    }

    /**
     * 查询黑名单
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryBlackList(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();

        IPage<BlackList> blackListIPage = this.blackListService.queryBlackList(user.getId(), page, pageSize);

        PageResult pageResult = new PageResult();
        pageResult.setPages(new Long(blackListIPage.getPages()).intValue());
        pageResult.setCounts(new Long(blackListIPage.getTotal()).intValue());
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        List<BlackList> records = blackListIPage.getRecords();
        List<Long> idList = new ArrayList<>();
        for (BlackList record : records) {
            idList.add(record.getBlackUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", idList);
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);

        List<BlackListVo> blackListVoList = new ArrayList<>();
        for (BlackList record : records) {
            for (UserInfo userInfo : userInfos) {
                if (record.getBlackUserId() == userInfo.getUserId()) {
                    BlackListVo blackListVo = new BlackListVo();
                    blackListVo.setId(userInfo.getUserId());
                    blackListVo.setAvatar(userInfo.getLogo());
                    blackListVo.setNickname(userInfo.getNickName());
                    blackListVo.setGender(userInfo.getSex().name().toLowerCase());
                    blackListVo.setAge(userInfo.getAge());
                    blackListVoList.add(blackListVo);
                }
            }
        }

        pageResult.setItems(blackListVoList);
        return pageResult;
    }

    /**
     * 移除黑名单
     * @param userId
     */
    public void delBlacklist(Long userId) {
        User user = UserThreadLocal.get();
        this.blackListService.delBlacklist(user.getId(), userId);
    }

    /**
     * 更新设置
     * @param likeNotification
     * @param pinglunNotification
     * @param gonggaoNotification
     */
    public void updateNotification(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        User user = UserThreadLocal.get();
        this.settingsService.updateNotification(user.getId(), likeNotification, pinglunNotification, gonggaoNotification);
    }
}
